<template>
  <el-dialog
    class="addedit-project-dialog"
    width="900px"
    :visible.sync="dialogVisible"
    :title="operType == 'add' ? '新增合同项目' : '修改合同项目'"
    :close-on-click-modal="false"
    v-dialogDrag="true"
    @open="handleDialogOpen"
    @closed="handleDialogClosed"
  >
    <el-form ref="addEditProjectForm" :model="formData" :rules="formRules" size="small" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目类型:" prop="itemType">
            <el-radio-group v-model="formData.itemType">
              <el-radio :label="1">自营项目</el-radio>
              <el-radio :label="2">分包项目</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="客户:" prop="entrustOrganizationId">
            <OrganizationSelect
              style="width: 100%;"
              ref="clientOrganizationSelect"
              v-model="formData.entrustOrganizationId"
            ></OrganizationSelect>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="项目名称:" prop="itemName">
            <el-input v-model="formData.itemName" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编号:" prop="itemNumber">
            <el-input v-model="formData.itemNumber" placeholder="请输入" :clearable="false">
              <div
                slot="suffix"
                style="color: #409EFF; cursor: pointer; padding: 0 5px;"
                @click="handleGenerateNumber"
              >自动生成</div>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="负责人:" prop="chargeUser">
            <el-select
              style="width: 100%;"
              v-model="formData.chargeUser"
              clearable
              filterable
            >
              <el-option
                v-for="(item, index) in userList"
                :key="index"
                :label="item.nickName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门:" prop="deptId">
            <el-select
              style="width: 100%;"
              v-model="formData.deptId"
              clearable
              filterable
            >
              <el-option
                v-for="(item, index) in saleDeptList"
                :key="index"
                :label="item.deptName"
                :value="item.deptId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="项目期限:" prop="itemDate">
            <el-date-picker
              style="width: 100%;"
              v-model="formData.itemDate"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :unlink-panels="true"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参与人:" prop="participant">
            <el-select
              style="width: 100%;"
              v-model="formData.participant"
              clearable
              filterable
            >
              <el-option
                v-for="(item, index) in userList"
                :key="index"
                :label="item.nickName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注:" prop="remark">
            <el-input
              type="textarea"
              rows="3"
              maxlength="100"
              show-word-limit
              v-model="formData.remark"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="附件:" prop="attachment">
            <el-upload
              ref="attachmentUploadRef"
              :action="uploadParams.url"
              :headers="uploadParams.headers"
              :before-upload="handleBeforeUpload"
              :on-success="handleSuccessFile"
              :on-error="handleErrorFile"
              :on-remove="handleRemoveFile"
              :on-preview="handlePreviewFile"
              :file-list="attachmentFileList"
              multiple
            >
              <el-button icon="el-icon-upload" size="mini" plain type="primary">添加附件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="dialog-footer" slot="footer">
      <el-button style="margin-right: 50px;" type="primary" @click="handleSave">保存</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { userListingIgnorePermission } from '@/api/system/user'
import { listDeptIgnorePermission } from '@/api/system/dept'
import {
  projectDetail,
  projectAdd,
  projectEdit,
  genItemNumber
} from '@/api/person/project'
import { getToken } from '@/utils/auth'

export default {
  name: 'AddEditProjectDialog',
  components: {},
  dicts: [],
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    operType: {
      type: String,
      default: 'add',
    },
    row: {
      type: Object,
      default: () => ({})
    },
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('update:show', value)
      }
    }
  },
  data() {
    return {
      userList: [],
      saleDeptList: [],
      formData: {},
      formRules: {
        itemType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        entrustOrganizationId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        itemName: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        itemNumber: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        chargeUser: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        deptId: [],
        itemDate: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        participant: [],
        remark: [],
        attachment: [],
      },
      // 文件上传参数
      uploadParams: {
        url: process.env.VUE_APP_BASE_API + '/system/oss/upload',
        headers: {
          Authorization: 'Bearer ' + getToken(),
          'Content-Disposition': 'inline'
        },
      },
      attachmentFileList: [],
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    // 弹框打开时
    handleDialogOpen() {
      if (this.operType == 'edit') {
        projectDetail(this.row.agreementItemId).then(res => {
          for (let key in this.formData) {
            this.formData[key] = res.data[key]
          }
          this.formData.itemDate = [res.data.beginTime, res.data.endTime]
          this.attachmentFileList = JSON.parse(res.data.attachment || '[]')
        }).catch(err => {})
        this.$nextTick(() => {
          this.$refs['clientOrganizationSelect'].setDefaultOption({
            entrustOrganizationId: this.row.entrustOrganizationId,
            organizationName: this.row.entrustOrganizationName
          })
        })
      }

      if (this.userList.length <= 0) {
        userListingIgnorePermission().then(res => {
          this.userList = res.data || []
        }).catch(err => {})
      }

      if (this.saleDeptList.length <= 0) {
        listDeptIgnorePermission({parentId: 0 }).then(res => {
          this.saleDeptList = res.data || []
        }).catch(err => {})
      }
    },
    // 弹框关闭时
    handleDialogClosed() {
      this.initFormData()
      this.$refs.addEditProjectForm.resetFields()
      this.attachmentFileList = []
    },
    // 初始化表单数据
    initFormData() {
      this.formData = {
        itemType: 1,
        entrustOrganizationId: '',
        itemName: '',
        itemNumber: '',
        chargeUser: '',
        deptId: '',
        itemDate: [],
        participant: '',
        remark: '',
        attachment: '',
      }
    },
    // 获取表单数据
    getFormData() {
      const data = JSON.parse(JSON.stringify(this.formData))
      data.beginTime = data.itemDate ? data.itemDate[0] : ''
      data.endTime = data.itemDate ? data.itemDate[1] : ''
      delete data.itemDate
      data.attachment = JSON.stringify(this.attachmentFileList?.map(item => ({
        ossId: item.response?.data.ossId || item.ossId,
        url: item.response?.data.url || item.url,
        name: item.response?.data.name || item.name
      })) || [])
      if (this.operType == 'edit') {
        data.agreementItemId = this.row.agreementItemId
      }
      return data
    },
    // 自动生成编号
    handleGenerateNumber() {
      if (!this.formData.chargeUser) {
        return this.$message.error('请先选择负责人')
      }
      if (!this.formData.itemDate || this.formData.itemDate.length <= 0) {
        return this.$message.error('请先选择项目期限')
      }
      const data = {
        chargeUser: this.formData.chargeUser,
        beginDate: this.formData.itemDate[0]
      }
      genItemNumber(data).then(res => {
        this.formData.itemNumber = res.data || ''
      }).catch(err => {})
    },
    // 点击保存
    handleSave() {
      this.$refs.addEditProjectForm.validate(valid => {
        if (!valid) return
        let fn = null
        if (this.operType == 'add') fn = projectAdd
        else if (this.operType == 'edit') fn = projectEdit
        const data = this.getFormData()
        fn(data).then(res => {
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.$emit('refresh')
        }).catch(err => {})
      })
    },

    // 文件上传前
		handleBeforeUpload(file) {
			// let isPDF = (file.type === 'application/pdf')
			// if (!isPDF) {
			// 	this.$message.warning('仅支持pdf格式，请重新上传!')
			// }
			// return isPDF
      return true
		},
    // 文件上传成功
    handleSuccessFile(res, file, fileList) {
			if (res.code == 500) {
				return this.$message.error(res.msg)
			}
			this.attachmentFileList = fileList
    },
    // 文件上传失败
    handleErrorFile(err, file, fileList) {
      this.$message.error('文件上传失败')
    },
    // 移除文件
    handleRemoveFile(file, fileList) {
      this.attachmentFileList = fileList
		},
    // 预览文件
    handlePreviewFile(file, fileList) {
			if (file.response && file.response.data) {
				window.open(file.response.data.url, 'PDF', '')
			} else if (file.url) {
				window.open(file.url, 'PDF', '')
			}
		},
  },
}
</script>

<style lang="scss" scoped>
.addedit-project-dialog {

  ::v-deep .el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
  }
}
</style>
